package org.daochong.lang;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public abstract class AbstractExpression implements Expression {

	private Charset defaultEncoding = Charset.defaultCharset();

	
	public Object eval(String expression) {
		return eval(expression, null);
	}

	
	public Object eval(File file) {
		return eval(file, defaultEncoding, null);
	}

	
	public Object eval(File file, Object obj) {
		return eval(file, defaultEncoding, obj);
	}

	
	public Object eval(File file, Charset encoding) {
		return eval(file, encoding, null);
	}

	
	public Object eval(File file, Charset encoding, Object obj) {
		try {
			if (file == null)
				return null;
			return eval(StringUtils.toString(new FileInputStream(file), encoding), obj);
		} catch (FileNotFoundException e) {
			throw new RuntimeException("Expression Fail: File not found" + e);
		}
	}

	
	public Object eval(Resource resource) {
		return eval(resource, defaultEncoding, null);
	}

	
	public Object eval(Resource resource, Object obj) {
		return eval(resource, defaultEncoding, obj);
	}

	
	public Object eval(Resource resource, Charset encoding) {
		return eval(resource, encoding, null);
	}

	
	public Object eval(Resource resource, Charset encoding, Object obj) {
		try {
			if (resource == null)
				return null;
			return eval(StringUtils.toString(resource.getInputStream(), encoding), obj);
		} catch (IOException e) {
			throw new RuntimeException("Expression Fail: File not found" + e);
		}
	}

	
	public Object eval(InputStream in) {
		return eval(in, defaultEncoding, null);
	}

	
	public Object eval(InputStream in, Object obj) {
		return eval(in, defaultEncoding, obj);
	}

	
	public Object eval(InputStream in, Charset encoding) {
		return eval(in, defaultEncoding, null);
	}

	
	public Object eval(InputStream in, Charset encoding, Object obj) {
		return eval(StringUtils.toString(in, encoding), obj);
	}

}
